var planCode = getQueryString("planCode");
var planId = getQueryString("planId");
var applyUnit = getQueryString("applyUnit");
var isQuery = getQueryString("isQuery");
var planType = getQueryString("planType");
$(function () {
    var queryUrl = '../sparepartrequdetail/list';
    var jqGridParam = {
        rownumWidth: 35,
        loadComplete: function (data) {
            if (data.page.userData) {
                $("#jqGrid").jqGrid("footerData", "set", {planPrice: '总计: ', money: data.page.userData.total});
            }
        },
        datatype:"local"
    };
    if (planId) {
        queryUrl += '?planId=' + planId;
        jqGridParam.colModel = [
            {label: '提出人', name: 'organUserName', index: 'ORGAN_USER', width: 60},
            {label: '需求车间', name: 'applyUnit', index: 'APPLY_UNIT', width: 70},
            {label: '备件编码', name: 'materialCode', index: 'MATERIAL_CODE', width: 80},
            {label: '计划编码', name: 'businessCode', index: 'BUSINESS_CODE', width: 80},
            {label: 'ERP编码', name: 'erpCode', index: 'ERP_CODE', width: 90},
            {label: '备件名称', name: 'materialName', index: 'MATERIAL_NAME', width: 90},
            {label: '规格型号', name: 'spec', index: 'SPEC'},
            {label: '单位', name: 'unit', index: 'UNIT', width: 50},
            {label: '备件性质', name: 'typeDesc', index: 'TYPE', width: 65},
            {label: '备件类型', name: 'installPosition', index: 'INSTALL_POSITION', width: 70},
            {
                label: 'ABC类', name: 'planAbc', index: 'PLAN_ABC', width: 45,
                cellattr: function(rowId, value, rawObject,row) {
                    var tooltipText = sysEnums.ABC_TYPE[value];
                    return 'title="' + tooltipText + '"';
                }
            },
            {label: '库存', name: 'stockNum', index: 'STOCK_NUM', width: 45},
            {label: '需求', name: 'demandNum', index: 'DEMAND_NUM', width: 45},
            {label: '在途', name: 'transitNum', index: 'TRANSIT_NUM', width: 45},
            {label: '预计使用时间', name: 'planeTime', index: 'PLANE_TIME', width: 95},
            {label: '订单生成时间', name: 'orderGenerateTime', index: 'PLANE_TIME', width: 95},
            {label: '预计到货时间', name: 'arriveTime', index: 'PLANE_TIME', width: 95},
            {label: '实际到货时间', name: 'actualArriveTime', index: 'PLANE_TIME', width: 95,
                cellattr:function (value, options, row) {
                    if (row.transitNum > 0){
                        if (row.transitNum <row.demandNum ){
                            return "style='background-color:rgba(255, 192, 0);'";
                        }
                    }
                }
            },
            {label: '到货周期', name: 'deliveryCycle', index: 'PLANE_TIME', width: 95},
            {label: '制造商', name: 'producor', index: 'PRODUCOR', width: 80},
            {label: '单价', name: 'planPrice', index: 'PLAN_PRICE', width: 60},
            {label: '金额', name: 'money', index: 'PLAN_PRICE*DEMAND_NUM', width: 60},
            {label: '备注', name: 'remark', sortable: false},
            {name: 'transitNum', hidden: true},
            {name: 'isCancelTransit', hidden: true},
            {name: 'organUser', hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {name: 'materialId', hidden: true}
        ];
        jqGridParam.footerrow = true;
    } else {
        vm.q.planType = 'RESULT';
        // vm.q.planAbc = '';

        jqGridParam.colModel = [
            // {label: '需求计划编码', name: 'planCode', index: 'PLAN_CODE', width: 80},
            {
                label: '计划类别', index: 'PLAN_TYPE', width: 50,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_NEEDS_PLAN_TYPE[row.planType];
                }
            },
            {label: '编制月份', name: 'organMonth', index: 'ORGAN_MONTH', width: 60},
            {label: '提出人', name: 'organUserName', index: 'ORGAN_USER', width: 50},
            {label: '备件名称', name: 'materialName', index: 'MATERIAL_NAME', width: 80},
            {label: '备件编码', name: 'materialCode', index: 'MATERIAL_CODE', width: 70},
            {label: 'ERP编码', name: 'erpCode', index: 'ERP_CODE', width: 70},
            {label: '规格型号', name: 'spec', index: 'SPEC'},
            {label: '计划编码', name: 'businessCode', index: 'BUSINESS_CODE', width: 80},
            {
                label: '预计到货时间', name: 'arriveTime', index: 'ARRIVE_TIME', width: 80,
                cellattr:function (rowId, val, rawObject ) {
                    if (rawObject.needsItemStatus == 'red') {
                        return "style='background-color:rgba(255, 0, 0,0.3)'";
                    } else if(rawObject.needsItemStatus == 'yellow'){
                        return "style='background-color:rgba(255, 255, 0,0.3)'";
                    }
                }

            },
            {label: '最近一次到货时间', name: 'actualArriveTime', index: 'ACTUAL_ARRIVE_TIME', width: 80},
            {label: '', name: 'needsItemStatus', index: 'NEEDS_ITEAN_STATUS', width: 80, hidden: true},
            {label: '需求', name: 'demandNum', index: 'DEMAND_NUM', width: 40},
            {
                label: '在途', name: 'transitNum', index: 'TRANSIT_NUM', width: 40,
                cellattr:function (rowId, val, rawObject ) {
                    if (rawObject.needsItemStatus == 'green') {
                        return "style='background-color:rgba(0,255,0,0.3)'";
                    }
                }
            },
            {label: '备注', name: 'remark', sortable: false,width:100},
            {name: 'isCancelTransit', hidden: true},
            {name: 'id',key: true, hidden: true}
        ];
    }
    // 设置URL
    jqGridParam.url = queryUrl;
    $("#jqGrid").Grid(jqGridParam);

    vm.getPlan(planId);
    vm.reload();
    vm.getExtracPlanList()
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "typeCode",
            pIdKey: "typePid",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        }
    },
    callback: {
        beforeCheck: true,
    }
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        planType: '',
        planAbc:'',
        sparePartRequDetail: {
            reserve2:'',
            devTypeName:'',
            devType:'',
            background:'',
            safeNum: '',
            money: '',
            planPrice: '',
            devName: '',
            devCode: '',
            deptDev: '',
            planeTime: '',
            demandNum: '',
            otwayPlan: '',
            producor:'',
            nowNum: '',
            planAbc:'',
            unit: '',
            spec: '',
            erpCode: '',
            materialName: '',
            materialCode: '',
            materialId: '',
            applyUnit: '',
            planCode: '',
            planId: '',
            id: ''
        },




        planType: 'PROCESS',
        ruleValidate: {
            materialId: [
                {required: true, message: '备件必选！', trigger: 'change'}
            ],
            demandNum: [
                {required: true, message: '需求数量不能为空！', type:"number", trigger: 'blur'}
            ],
            planeTime: [
                {required: true, message: '预计使用时间不能为空！',type:'date', trigger: 'blur'}
            ],
            devTypeName: [
                {required: true, message: '设备类型必填！', trigger: 'change'}
            ],
            reserve2: [
                {required: true, message: '图片必需上传！', trigger: 'change'}
            ],
            planPrice: [
                {
                    validator: (rule, value, callback) => {
                        if (!value) {
                            callback(new Error('计划单价不能为空！'));
                        }else {
                            callback();
                        }
                    },
                    trigger: 'blur',
                }]
        },

        organMonth: [], // 维修开始查询时间区间
        q: {
            planAbc:'', // ABC类
            applyDept: '', // 需求车间
            startDate:'',
            endDate:'',
            sparePartName: '', // 备件名称
            sparePartSpec: '', // 备件规格
            organName: '', // 需求项提出人
            planType: '', // 计划类型
            erpCode: '',// ERP编码
            warningDays:'',//距离实际到货时间还差
            delayDays:'',//已经超出实际到货时间
        },
        sparePartOut: {
            delFlag: 1,
            remark: '',
            useDevId: '',
            useDevName: '',
            useDevCode: '',
            pickNoId: '',
            pickNo: '',
            repairNoId: '',
            repairNo: '',
            backNum: '',
            initNum: '',
            outNum: '',
            cargoLocation: '',
            partUnit: '',
            spec: '',
            name: '',
            partCode: '',
            outStoreId: '',
            outStore: '',
            useUnit: '',
            outDate: new Date(),
            outCode: '',
            id: '',
            checkDate: '',
            checkStatus: '1', //未审核
            checkUser: '',
            updateDate: '',
            updateUser: '',
            createUser: '',
            createDate: '',
            devTypeName: '',
            devType: ''
        },
        auditTableData: [], // 审批table数据
        approveSparePartList: [], // 审核备件名称列表，审核窗口展示用
        rejectRemarkList: [], // 展示审批的备件中是否有已拒绝过得备件信息
        // 审核参数VO
        approveParam: {
            approveSparePartIdList: [],
            status: 1,
            remark: ''
        },
        isQuery: isQuery,
        uploadData: {},
        workshopList: [],// 所属车间下拉option列表
        planTypeList: enumsToListWithoutChange('SPARE_NEEDS_PLAN_TYPE'),
        abcArray:enumsToListWithoutChange('ABC_TYPE'),
        cancelShow:false,//是否展示
        cancelOneTheWayForm:{
            requDetailIdList:[],//取消在途单子id
            remark:''
        },
        ruleCancelOneTheWay:{
            remark:[
                {
                    required:true,  message:'请输入备注',trigger: 'blur'
                }
            ]
        },
        planCodeList:[],//计划编码列表
        extractPlanShow:false,
        extractPlanForm:{
            targetRequId:'',
            requDetailIdList:[]
        },
        planList:[],
        extractPlanRule:{
            targetRequId:[
                {
                    required:true,  message:'请选择过程计划',trigger: 'change'
                }
            ]
        },
        threeYearsInformation:{
            yearlyLyItems:[
                {
                    lyQuantity:'',
                    years:''
                },
                {
                    lyQuantity:'',
                    years:''
                },
                {
                    lyQuantity:'',
                    years:''
                }
            ],
            stockNum:'',
            xbkNum:'',
            transitNum:'',
            zzwxQuantity:'',
            wwwxQuantity:''
        },
        SpThjStatList:{
            stockNum:'',
            xbkNum:'',
            transitNum:'',
            zzwxQuantity:'',
            wwwxQuantity:'',
            xqjhQuantity:''
        },
        isRemarkRequired:false,
    },
    created: function () {
        this.loadWorshopList();
    },
    /*mounted() {
        this.getRemarkPlaceholder();
    },*/
    methods: {
        // 上传图片
        handleSuccess: function (res, file) {
            vm.sparePartRequDetail.reserve2 = file.response.url;
            var url = vm.sparePartRequDetail.reserve2;
            if (url) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
            }
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传格式正确的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 5M。'
            });
        },
        //查看图片
        eyeFile: function (url) {
            if (url) {
                window.open(url);
            } else {
                alert('还未上传文件');
            }
        },
        /**
         *加载设备树
         */
        getTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../devtype/listAll',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    var node = ztree.getNodeByParam("typeCode", vm.sparePartRequDetail.devTypeName);
                    if (node) {
                        ztree.selectNode(node);
                        if (node.devTypeName) {
                            vm.sparePartRequDetail.devTypeName = node.devTypeName;
                        } else {
                            vm.sparePartRequDetail.devTypeName = '无';
                        }
                    } else {
                        node = ztree.getNodeByParam("id", "0");
                        ztree.selectNode(node);
                    }
                }
            });
        },
        devTypeShow: function () {
            var _this = this;
            openWindow({
                title: "选择设备类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes = ztree.getSelectedNodes();
                    if (nodes && nodes.length > 0) {
                        var current = nodes[0];
                        if (current.level == 2) {
                            vm.sparePartRequDetail.devType = current.typeCode;
                            vm.sparePartRequDetail.devTypeName = current.typeName;
                            layer.close(index);
                        } else {
                            alert('请选择设备设备小类！');
                        }
                    } else {
                        alert('请选择一条记录！');
                    }
                    console.log(vm.sparePartRequDetail)
                }
            });
        },
        zhPlanAbc(planAbc){
            return sysEnums.ABC_TYPE(planAbc)
        },
        /**
         * 备件提示
         */
        getRemarkPlaceholder() {
            setTimeout(() => {
                let placeholders = '';
                vm.sparePartRequDetail.background = '';

                if (this.threeYearsInformation.stockNum > 0 || this.threeYearsInformation.xbkNum > 0) {
                    placeholders += `ERP库/线边库中该备件分别有${this.threeYearsInformation.stockNum}/${this.threeYearsInformation.xbkNum}个，请确认需求是否合理! \n`;
                }
                if (this.SpThjStatList.stockNum > 0) {
                    placeholders += `该备件有${this.SpThjStatList.stockNum}个备件可替代且有库存，请确认需求是否合理! \n`;
                }
                if (this.threeYearsInformation.transitNum > 0) {
                    placeholders += `SRM中该备件有${this.threeYearsInformation.transitNum}个订单正在执行中，请确认需求是否合理! \n`;
                }
                if (this.threeYearsInformation.zzwxQuantity > 0 || this.threeYearsInformation.wwwxQuantity > 0) {
                    placeholders += `该型号备件有${this.threeYearsInformation.zzwxQuantity + this.threeYearsInformation.wwwxQuantity}个正处于待修/维修流程中，请确认需求是否合理! \n`;
                }

                vm.sparePartRequDetail.background = placeholders;
                console.log("提示:", vm.sparePartRequDetail);
                console.log("提示:", vm.sparePartRequDetail.background);
            }, 100);
        },
        /**
         * 替换件列表
         */
        addReplace(){
            if(!vm.sparePartRequDetail.materialId){
                alert('请先选中备件！');
                return ;
            }
            let ids = vm.sparePartRequDetail.materialId
            openWindow({
                type: 2,
                title: '<i class="fa fa-plus-circle"></i> 替换件',
                content: '../spare/sparedev.html?spareId=' + ids
            })
        },
        //获取过程计划
        getExtracPlanList(){
            Ajax.request({
                url: "../sparepartrequ/list?page=1&limit=100000&planType=PROCESS",
                async: true,
                successCallback: function (res) {
                    let data = res.page.list;
                    vm.planList = []
                    data.forEach(item=>{
                         vm.planList.push({
                             name:item.planCode,
                             id:item.id
                         })
                    })
                }
            });
        },
        //提取计划
        extractPlan:function (){
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            vm.extractPlanForm.requDetailIdList = ids;
            //获取新的过程计划

          this.extractPlanShow = true
        },
        extractPlanOk(){
            console.log(vm.extractPlanForm)
            const that =this;
            this.$refs['extractPlant'].validate((valid) => {
                if (valid) {
                    confirm('是否确认提取此项计划？', function () {
                        Ajax.request({
                            url: "../sparepartrequdetail/addFromOldRequ",
                            params: JSON.stringify(that.extractPlanForm),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function () {
                                alert('操作成功', function (index) {
                                    vm.extractPlanCancel()
                                    vm.reload();
                                });
                            }
                        });
                    });
                } else {
                    this.$Message.error('请输入!');
                }
            })
        },
        apply: function () {
            // 校验是否选中记录
            var selectedSparePartList = getSelectedRowDatas('#jqGrid');
            if (!selectedSparePartList || selectedSparePartList.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }

            // 校验是否有上次审批不通过信息
            vm.rejectRemarkList = [];

            // 已审核的备件不允许重复审核
            vm.approveSparePartList = [];
            vm.approveParam = {
                approveSparePartIdList: [],
                status: '1',
                remark: ''
            }
            for (var i = 0; i < selectedSparePartList.length; i++) {
                if (selectedSparePartList[i].status == 1) {
                    alert('备件[' + selectedSparePartList[i].name + ']已通过审核，请取消选中！');
                    return;
                } else if (selectedSparePartList[i].status == 2 && selectedSparePartList[i].reserve3) {
                    vm.rejectRemarkList.push(selectedSparePartList[i].name + '[' + selectedSparePartList[i].partCode + ']' + ' : ' + selectedSparePartList[i].reserve3)
                }
                vm.approveSparePartList.push(selectedSparePartList[i].materialName + '[' + selectedSparePartList[i].materialCode + ']');
                vm.approveParam.approveSparePartIdList.push(selectedSparePartList[i].id);
            }
            openWindow({
                title: "备件审核",
                area: ['600px', '450px'],
                content: jQuery("#apply"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../sparepart/Approval',
                        params: JSON.stringify(vm.approveParam),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            layer.close(index);
                            alert('审核完毕', function (index) {
                                vm.reload();
                            });
                        }
                    });
                }
            });
        },

        extractPlanCancel(){
            vm.extractPlanForm.requDetailIdList = [];
            vm.extractPlanForm.targetRequId = '';
            this.$set(this.extractPlanForm,'targetRequId','')
            this.extractPlanShow = false;
            let data = JSON.parse(JSON.stringify(this.planList))
            this.planCodeList = [...data]
        },
        //取消在途确认
        okOnTheWay:function (){
            const that =this;
            this.$refs.onTheWayValidate.validate((valid) => {
                if (valid) {
                    confirm('是否确认要取消在途数？', function () {
                        Ajax.request({
                            url: "../sparepartrequdetail/cancelTransit",
                            params: JSON.stringify(that.cancelOneTheWayForm),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function () {
                                alert('操作成功', function (index) {
                                    vm.cancelOnTheWay()
                                    vm.reload();
                                });
                            }
                        });
                    });
                } else {
                    this.$Message.error('请填写取消在途原因!');
                }
            })
        },
        //取消取消在途
        cancelOnTheWay(){
            this.cancelShow = false;
            this.planCodeList = [];
            this.cancelOneTheWayForm = {
                requDetailIdList:[],
                remark:''
            }
        },
        handleRepairStartRangeChange(dateVal, dateType) {
            this.q.startDate = dateVal[0];
            this.q.endDate = dateVal[1];
        },
        loadWorshopList: function () {
            var _this = this;
            Ajax.request({
                url: '../sys/dept/listByDeptLevel?deptLevel=2',
                async: true,
                successCallback: data => {
                    this.workshopList = data.list;
                }
            });
        },
        getSpareInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: '../spare/sparePartSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    console.log(res)
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        //在这拉取近三年用量和库存信息
                        vm.usageAndInventory(res.id)
                        vm.getSpThjStat(res.id)
                        if (parseInt(res.stockNum) > 0 || parseInt(res.transitNum) > 0) {
                            layer.confirm('当前备件有库存或者在途中，是否仍要列入需求计划？', {icon: 3, title: '需求确认提示'},
                                function (confirmIndex) {
                                    vm.sparePartRequDetail.materialId = res.id;
                                    vm.sparePartRequDetail.devTypeName = res.devTypeName;
                                    vm.sparePartRequDetail.devType = res.devType;
                                    vm.sparePartRequDetail.materialCode = res.partCode;
                                    vm.sparePartRequDetail.materialName = res.name;
                                    vm.sparePartRequDetail.erpCode = res.erpCode;
                                    vm.sparePartRequDetail.spec = res.spec;
                                    vm.sparePartRequDetail.unit = res.unit;
                                    vm.sparePartRequDetail.nowNum = res.stockNum;
                                    vm.sparePartRequDetail.transitNum = res.transitNum;
                                    vm.sparePartRequDetail.producor = res.producor;
                                    vm.sparePartRequDetail.planAbc = res.planAbc;
                                    vm.sparePartRequDetail.safeNum = res.safeNum;
                                    vm.sparePartRequDetail.planPrice = res.price;
                                    vm.sparePartRequDetail.reserve2 = res.reserve2;
                                    if(vm.sparePartRequDetail.reserve2 == "http://10.107.250.31:9000/erms/sparepart/image/nopicture.jpg"){
                                        console.log("sparePartRequDetail.reserve1",vm.sparePartRequDetail.reserve2)
                                        vm.sparePartRequDetail.reserve2 = '';
                                        console.log("sparePartRequDetail.reserve2",vm.sparePartRequDetail.reserve2)
                                    }
                                    layer.close(confirmIndex);
                                    layer.close(index);
                                    vm.getRemarkPlaceholder();
                                }
                            );
                        } else {
                            vm.sparePartRequDetail.devTypeName = res.devTypeName;
                            vm.sparePartRequDetail.devType = res.devType;
                            vm.sparePartRequDetail.materialId = res.id;
                            vm.sparePartRequDetail.materialCode = res.partCode;
                            vm.sparePartRequDetail.materialName = res.name;
                            vm.sparePartRequDetail.spec = res.spec;
                            vm.sparePartRequDetail.erpCode = res.erpCode;
                            vm.sparePartRequDetail.unit = res.unit;
                            vm.sparePartRequDetail.nowNum = res.stockNum;
                            vm.sparePartRequDetail.transitNum = res.transitNum;
                            vm.sparePartRequDetail.producor = res.producor;
                            vm.sparePartRequDetail.planAbc = res.planAbc;
                            vm.sparePartRequDetail.safeNum = res.safeNum;
                            vm.sparePartRequDetail.planPrice = res.price;
                            vm.sparePartRequDetail.reserve2 = res.reserve2;
                            if(vm.sparePartRequDetail.reserve2 == "http://10.107.250.31:9000/erms/sparepart/image/nopicture.jpg"){
                                console.log("sparePartRequDetail.reserve1",vm.sparePartRequDetail.reserve2)
                                vm.sparePartRequDetail.reserve2 = '';
                                console.log("sparePartRequDetail.reserve2",vm.sparePartRequDetail.reserve2)
                            }
                            layer.close(index);
                            vm.getRemarkPlaceholder();
                        }

                    }
                }
            })
        },
        usageAndInventory(ids){
            Ajax.request({
                url: '../sparepart/getSparePartStat'+'?id='+ids,
                async: true,
                successCallback: function (data) {
                    vm.threeYearsInformation = data.statResult;
                }
            });
        },
        getSpThjStat(ids){
          Ajax.request({
              url:'../sparepart/getSpThjStat?id='+ids,
              asyncL:true,
              successCallback:function(data){
                  vm.SpThjStatList = data.statResult
              }
          })
        },
        query: function () {
            vm.reload();
        },
        //进行自动计算
        doSum: function () {
            var demandNum = vm.sparePartRequDetail.demandNum;
            if (demandNum <= 0) {
                demandNum = Math.abs(demandNum);
                vm.sparePartRequDetail.demandNum = demandNum;
            }
            var planPrice = vm.sparePartRequDetail.planPrice;
            var total = demandNum * planPrice;
            vm.sparePartRequDetail.money = total;
        },
        //更新订单时间，
        upOrderTime:function () {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.sparePartRequDetail = {
                reserve2: '',
                devTypeName: '',
                devType: '',
                background: '',
                money: '',
                planPrice: '', // 计划价格
                devName: '',
                devCode: '',
                deptDev: '',
                planeTime: '',
                demandNum: '',
                otwayPlan: '',
                nowNum: '',
                unit: '',
                spec: '',
                materialName: '',
                materialCode: '',
                materialId: '',
                safeNum: 0,
                applyUnit: applyUnit,
                planCode: planCode,
                planId: planId
            };
            vm.threeYearsInformation = {
                yearlyLyItems: [
                    {
                        lyQuantity: '',
                        years: ''
                    },
                    {
                        lyQuantity: '',
                        years: ''
                    },
                    {
                        lyQuantity: '',
                        years: ''
                    }
                ],
                stockNum: '',
                xbkNum: '',
                transitNum: '',
                zzwxQuantity: '',
                wwwxQuantity: ''
            };
            vm.SpThjStatList = {
                stockNum: '',
                xbkNum: '',
                transitNum: '',
                zzwxQuantity: '',
                wwwxQuantity: '',
                xqjhQuantity: ''
            };
            vm.getTreeShow();
            this.$nextTick(() => this.$refs.materialNameInput.focus());
        },
        cancel: function () {
            var dataList = getSelectedRowDatas('#jqGrid');
            if (!dataList || dataList.length == 0) {
                return alert('请选中要取消在途的记录！');
            }
            for (let i = 0; i < dataList.length; i++) {
                var data = dataList[i];
                // 只可以取消终版计划的在途
                if (data.planType === 'PROCESS') {
                    alert('只可以取消终版计划的在途！');
                    return;
                }
                if(data.isCancelTransit == 1){
                    alert('备件[' + data.materialName + ']已取消在途，请移除！');
                    return;
                }
                if (data.transitNum === '0') {
                    alert('备件[' + data.materialName + ']在途数已为0，无需取消在途！');
                    return;
                }
                this.planCodeList.push(data.businessCode)
                this.cancelOneTheWayForm.requDetailIdList.push(data.id)
            }
            this.cancelShow = true
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var datas = getSelectedRowDatas("#jqGrid");
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(datas[0].id);
            //在这开始拉近三年信息
            vm.usageAndInventory(datas[0].materialId);
            vm.getSpThjStat(datas[0].materialId);
            vm.getTreeShow();
            this.$nextTick(() => {
                this.$refs.materialNameInput.focus();

                this.getRemarkPlaceholder();
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.sparePartRequDetail.id == null ? "../sparepartrequdetail/save" : "../sparepartrequdetail/update";
            //执行自动计算
            vm.doSum();
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.sparePartRequDetail),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid")
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartrequdetail/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../sparepartrequdetail/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.sparePartRequDetail = r.sparePartRequDetail;
                    if(vm.sparePartRequDetail.reserve2 == "http://10.107.250.31:9000/erms/sparepart/image/nopicture.jpg"){
                        console.log("sparePartRequDetail.reserve1",vm.sparePartRequDetail.reserve2)
                        vm.sparePartRequDetail.reserve2 = '';
                        console.log("sparePartRequDetail.reserve2",vm.sparePartRequDetail.reserve2)
                    }
                }
            });

        },
        getPlan: function (planId) {
            if (planId) {
                Ajax.request({
                    url: "../sparepartrequ/info/" + planId,
                    async: true,
                    successCallback: function (r) {
                        if (r.sparePartRequ && r.sparePartRequ != 'null') {
                            vm.planType = r.sparePartRequ.planType;
                        }
                    }
                });
            }
        },
        reload: function (event) {
            vm.showList = true;
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var param = {};
            if (vm.q.startDate) {
                param.startDate = gmt2DateStr(vm.q.startDate);
            }
            if (vm.q.endDate) {
                param.endDate = gmt2DateStr(vm.q.endDate);
            }
            if (vm.q.applyDept) {
                param.applyDept = vm.q.applyDept;
            }
            if (vm.q.sparePartName) {
                param.sparePartName = vm.q.sparePartName;
            }
            if (vm.q.sparePartSpec) {
                param.sparePartSpec = vm.q.sparePartSpec;
            }
            if (vm.q.organName) {
                param.organName = vm.q.organName;
            }
            if (vm.q.erpCode) {
                param.erpCode = vm.q.erpCode;
            }
            if (vm.q.planType) {
                param.planType = vm.q.planType;
            }
            if (vm.q.planAbc) {
                param.planAbc = vm.q.planAbc;
            }
            if (vm.q.warningDays) {
                param.warningDays = vm.q.warningDays;
            }
            if (vm.q.delayDays) {
                param.delayDays = vm.q.delayDays;
            }
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: param,
                page: page,
                datatype:'json'
            }).trigger("reloadGrid");
        },
        reloadSearch: function () {
            vm.q = {
                planAbc:'',//abc
                applyDept: '', // 编制单位
                startDate:'',
                endDate:'',
                sparePartName: '', // 备件名称
                sparePartSpec: '', // 备件规格
                organName: '',
                planType: '',
                erpCode: '',
                warningDays:'',//已经超出实际到货时间
                delayDays:'',//距离实际到货时间还差

            };
            this.organMonth = [];
            vm.reload();
        },
        handleSubmit: function (name) {
            let _this = this;
            if((vm.sparePartRequDetail.background && !vm.sparePartRequDetail.remark)){
                alert('需求原因备注未填！')
                return
            }
            if (vm.sparePartRequDetail.safeNum > 0 && vm.sparePartRequDetail.demandNum > vm.sparePartRequDetail.safeNum) {
                layer.confirm('备件需求数大于安全库存，是否仍要列入需求计划？', {icon: 3, title: '需求确认提示'},
                    function (index) {
                        if (!vm.sparePartRequDetail.remark){
                            alert('该备件存在在途或有库存，提交需求必须添加备注信息！')
                            return
                        }
                        layer.close(index);
                        handleSubmitValidate(_this, name, function () {
                            vm.saveOrUpdate()
                        });
                    }
                );
            } else {
                handleSubmitValidate(_this, name, function () {
                    vm.saveOrUpdate()
                });
            }
        },
        handleReset: function (name) {
            vm.sparePartRequDetail.materialName = '',
            handleResetForm(this, name);
        },
        exportData: function () {
            let queryConditionArray = [];
            if (this.q.planType) {
                queryConditionArray.push('planType=' + this.q.planType);
            }
            if (this.q.planAbc) {
                queryConditionArray.push('planAbc=' + this.q.planAbc);
            }
            if (this.q.daterange) {
                queryConditionArray.push('daterange=' + this.q.daterange);
            }
            if (this.q.applyDept) {
                queryConditionArray.push('applyDept=' + this.q.applyDept);
            }
            if (this.q.sparePartName) {
                queryConditionArray.push('sparePartName=' + this.q.sparePartName);
            }
            if (this.q.sparePartSpec) {
                queryConditionArray.push('sparePartSpec=' + this.q.sparePartSpec);
            }
            if (this.q.erpCode) {
                queryConditionArray.push('erpCode=' + this.q.erpCode);
            }
            if (this.q.organName) {
                queryConditionArray.push('organName=' + this.q.organName);
            }
            if (this.q.warningDays) {
                queryConditionArray.push('warningDays=' + this.q.warningDays);
            }
            if (this.q.delayDays) {
                queryConditionArray.push('delayDays=' + this.q.delayDays);
            }
            let exportUrl = '../sparepartrequdetail/exportData'
            if (queryConditionArray.length > 0) {
                exportUrl += '?' + queryConditionArray.join('&')
            }
            window.open(exportUrl, '_blank');
        },
        handleBeforeUploadExcel: function () {
            this.$refs.uploadFile.clearFiles();
            this.uploadData = {
                planId: planId
            };
            let promise = new Promise((resolve) => {
                this.$nextTick(function () {
                    resolve(true)
                })
            });
            return promise
        },
        handleBeforeUploadExcel2: function () {
            this.$refs.uploadFile2.clearFiles();
            this.uploadData = {
                planId: planId
            };
            let promise = new Promise((resolve) => {
                this.$nextTick(function () {
                    resolve(true)
                })
            });
            return promise
        },
        handleImportExcelSuccess: function (res, file) {
            if (res.code == 0) {
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.err
                })
            }
        },
        handleExcelFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleImportExcelError: function (err, file) {
            alert('导入失败');
        },
        GMTToStr: function (time) {
            var date = new Date(time)
            var month = date.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            return date.getFullYear() + '-' + month;
        }
    }

});
